package com.coder.network

import okhttp3.Cache
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.*
import java.util.concurrent.TimeUnit

/**
 *
 * @author yuhushuan
 * @date 2020/11/6 20:24
 */
open class NetworkApi {

    private val mRetrofitMap = HashMap<String, Retrofit>()
    private val mOkHttpClient by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { getOkHttpClient() }


    open fun getOkHttpClient(): OkHttpClient {
        val builder = OkHttpClient.Builder()

        builder.connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)

        intercept(builder)
        if (isDebug()) {
            builder.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
        }
        return builder.build()
    }

    fun <T> getService(baseUrl: String, service: Class<T>): T {
        var retrofit = mRetrofitMap[baseUrl + service.name]
        if (retrofit == null) {
            val builder = Retrofit.Builder()
            builder.baseUrl(baseUrl)
                    .client(mOkHttpClient)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            retrofit = builder.build()
            mRetrofitMap[baseUrl + service.name] = retrofit
        }
        return retrofit!!.create(service)
    }

    open fun isDebug() = false

    open fun intercept(builder: OkHttpClient.Builder): OkHttpClient.Builder {
        return builder
    }


}